import 'package:get/get.dart';
import 'package:wallet_utils/toast.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'base_pager_respository.dart';
import 'options.dart';

/// @author: pengboboer
/// @createDate: 2022/1/11
mixin PagerMixin<D, T extends BasePagerBean<D>> on GetxController {
  List<D> _list = [];
  int _currentPage = FIRST_PAGE;
  bool _isShowEmpty = false;
  bool _isShowLoading = true;
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  late BasePagerRepository _repository;

  @override
  void onInit() {
    super.onInit();
    _repository = _createRepository();
  }

  BasePagerRepository _createRepository() {
    return BasePagerRepository<D, T>(
        pagerOptions: createPagerOptions(),
        refreshOptions: RefreshOptions<D>(onGetPageData: (list) {
          _list = list;
          _isShowEmpty = _list.isEmpty;
          update();
        }, onRefreshError: (String msg) {
          _refreshController.refreshFailed();
          if (msg.contains('数据异常') || msg.contains('请求失败')) {
            return;
          }
          ToastUtils.showToast(msg);
        }, onLoadMoreError: (String msg) {
          _refreshController.loadFailed();
          if (msg.contains('数据异常') || msg.contains('请求失败')) {
            return;
          }
          ToastUtils.showToast(msg);
        }, onFinishLoad: () {
          _refreshController.loadComplete();
        }, onFinishRefresh: () {
          _refreshController.refreshCompleted(resetFooterState: false);
          _isShowLoading = false;
          update();
        }, onNoMoreData: (bool noMore) {
          noMore
              ? _refreshController.loadNoData()
              : _refreshController.resetNoData();
        }, onCurrentPage: (page) {
          _currentPage = page;
        }));
  }

  void onRefresh({bool isResetLoading = true}) {
    bool isShow = _isShowLoading;
    _isShowLoading = isResetLoading;

    /// 需要重置loading状态，并且之前的loading状态为false的时候，才需要刷新页面
    /// 如果发生了错误 setState() or markNeedsBuild() called during build.
    /// 要注意你旧的GetxController可能没有释放
    if (isResetLoading && !isShow) update();
    _repository.refresh();
  }

  void onLoadMore() => _repository.loadMore();

  List<D> get list => _list;

  int get currentPage => _currentPage;

  bool get isShowEmpty => _isShowEmpty;

  bool get isShowLoading => _isShowLoading;

  RefreshController get refreshController => _refreshController;

  PagerOptions<T> createPagerOptions();
}

